﻿
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Core;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Xml;

namespace Yuanlin.Business
{
    public class TemplateEditControl : YuanlinUserControl
    {
        protected ValuedTextBox titleValuedTextBox;
        protected ValuedDropDownList isDefaultDropDownList;

        protected IButton SaveButton;
        protected IButton BackButton;
        private string templateValue = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TemplateValue);

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack && !AjaxManager.IsCallBack)
            {
                BindDropdownList();
                Bind();
            }
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
        }

        private void BindDropdownList()
        {
            isDefaultDropDownList.Items.Clear();
            isDefaultDropDownList.Items.Add(new ListItem(string.Empty, string.Empty));
            isDefaultDropDownList.Items.Add(new ListItem("false", "false"));
            isDefaultDropDownList.Items.Add(new ListItem("true", "true"));
        }

        private void Bind()
        {
            XmlNode xmlNode = Templates.Instance().GetNodeByAttribute("root/Item", "Value", templateValue);

            if (xmlNode != null)
            {
                this.titleValuedTextBox.Value = xmlNode.Attributes["Name"].Value;
                this.isDefaultDropDownList.SelectedValue = xmlNode.Attributes["IsDefault"].Value;
            }   
        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect(SiteUrls.Instance().GetTemplateListUrl());
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            XmlNode xmlNode = Templates.Instance().GetNodeByAttribute("root/Item", "Value", templateValue);

            Templates.Instance().UpdateAttribute(xmlNode, "IsDefault", isDefaultDropDownList.SelectedValue);
            Templates.Instance().UpdateAttribute(xmlNode, "Name", titleValuedTextBox.Text);
            Templates.Instance().Save();

            Page.Response.Redirect(SiteUrls.Instance().GetTemplateListUrl());

        }

    }
}